<template>
  <div class="role">
    <pageSearch :searchFormConfig="searchFormConfig" />
    <pageTalbe
      ref="pageTableRef"
      :tableConfig="tableConfig"
      pageName="role"
      @newBtnClick="handleNewData"
      @editBtnClick="handleDditData"
    />
    <pageModal
      ref="pageModalRef"
      :modalConfig="modalConfig"
      :otherInfo="otherInfo"
      pageName="role"
      :defaultInfo="defaultInfo"
    >
      <div class="menu-tree">
        <el-tree
          ref="ElTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          @check="handleCheck"
          :props="{ children: 'children', label: 'name' }"
        />
      </div>
    </pageModal>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, ref } from 'vue'
import { useStore } from 'vuex'
import { ElTree } from 'element-plus'

import { searchFormConfig } from './config/search.config'
import { tableConfig } from './config/table.config'
import { modalConfig } from './config/modal.config'

import pageSearch from '@/components/page-search'
import pageTalbe from '@/components/page-table'
import pageModal from '@/components/page-modal'

import { usePageModal } from '@/hook/page-modal-hook'
import { menuMapLeafKeys } from '@/utils/map-menus'

export default defineComponent({
  name: 'role',
  components: {
    pageSearch,
    pageTalbe,
    pageModal
  },
  setup() {
    const store = useStore()
    const menus = computed(() => store.state.entireMenu)
    const ElTreeRef = ref<InstanceType<typeof ElTree>>()
    const editCallback = (row: any) => {
      const leafKeysId = menuMapLeafKeys(row.menuList)
      nextTick(() => {
        ElTreeRef.value?.setCheckedKeys(leafKeysId, false)
      })
    }
    const otherInfo = ref({})
    const handleCheck = (data1: any, data2: any) => {
      const checkedKeys = data2.checkedKeys
      const halfCheckedKeys = data2.halfCheckedKeys
      const menuList = [...checkedKeys, ...halfCheckedKeys]
      otherInfo.value = { menuList }
    }
    const [pageModalRef, defaultInfo, handleNewData, handleDditData] =
      usePageModal(undefined, editCallback)
    return {
      searchFormConfig,
      tableConfig,
      modalConfig,
      pageModalRef,
      defaultInfo,
      handleNewData,
      handleDditData,
      menus,
      otherInfo,
      handleCheck,
      ElTreeRef
    }
  }
})
</script>

<style scoped lang="less">
.menu-tree {
  margin-left: 38px;
}
</style>
